import { login, register, certificateSinger } from '@/api/user';

const defaultUser = {
  username: 'test',
  nickname: '测试用户',
  certificated: true,
};

const mockKey = 'MOCK_USER';
let currentUser = localStorage.getItem(mockKey) || null;
if (currentUser) {
  currentUser = JSON.parse(currentUser);
}

const app = {
  state: {
    logged: !!currentUser,
    currentUser,
  },
  mutations: {
    LOGGED_USER: (state, user) => {
      state.currentUser = user;
      state.logged = true;
    },
    LOGOUT_USER: (state) => {
      state.logged = false;
      state.currentUser = null;
    },
  },
  actions: {
    login({ commit }, user = defaultUser) {
      return new Promise((resolve, reject) => {
        login(user).then((res) => {
          const { meta, data } = res;
          if (meta.success && meta.code === 6666) {
            const combined = { ...user, ...data };
            commit('LOGGED_USER', combined);
            localStorage.setItem(mockKey, JSON.stringify(combined));
            resolve();
          } else {
            reject(meta);
          }
        });
      });
    },
    register(_, user) {
      return new Promise((resolve, reject) => {
        register(user).then((data) => {
          const { meta } = data;
          if (meta.success && meta.code === 6666) {
            resolve(meta);
          } else {
            reject(meta);
          }
        });
      });
    },
    certificate(_, payload) {
      return new Promise((resolve, reject) => {
        certificateSinger(payload)
          .then((data) => {
            const { meta } = data;
            if (meta.success && meta.code === 6666) {
              resolve(meta);
            } else {
              reject(meta);
            }
          });
      });
    },
    logout({ commit }) {
      commit('LOGOUT_USER');
      localStorage.removeItem(mockKey);
    },
  },
  getters: {
    logged: state => state.logged,
    currentUser: state => state.currentUser,
  },
};

export default app;
